package com.nwork.qingmanhua.imagedown;

import android.os.Environment;
import android.text.TextUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class ImgFileManager {
	private static String sdFolder = "";
	private static String imgFolder = "/qianfeng/imgs/";

	private static String getSDFolder() {
		if (TextUtils.isEmpty(sdFolder)) {
			sdFolder = Environment.getExternalStorageDirectory().getPath();
		}
		return sdFolder;
	}

	public static byte[] getBitmap(String url) {
		if (TextUtils.isEmpty(url)) {
			return null;
		}
		File folder = new File(getSDFolder() + imgFolder);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		String name = MD5.MD5Encode(url) + ".img";
		File file = new File(folder + name);
		if (!file.exists()) {
			return null;
		}
		FileInputStream fis = null;
		ByteArrayOutputStream baos = null;
		try {
			fis = new FileInputStream(file);
			baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int readed;
			while ((readed = fis.read(buffer)) != -1) {
				baos.write(buffer, 0, readed);
			}
			return baos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				if (baos != null) {
					baos.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static void saveBitmap(String url, byte[] data) {
		if (TextUtils.isEmpty(url) || data == null || data.length == 0) {
			return;
		}
		File folder = new File(getSDFolder() + imgFolder);
		if (!folder.exists()) {
			folder.mkdirs();
		}

		String name = MD5.MD5Encode(url) + ".img";
		File file = new File(folder + name);

		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			fos.write(data);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
